import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Progress, Tag, Checkbox, Button as AntdButton, Space, Tooltip, message, InputNumber, Modal, Typography } from 'antd';
// import { InputNumber } from '@/components/eai-design';
import { WarningOutlined, CheckCircleOutlined, PlusOutlined, EditOutlined, DeleteOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
import type { Key } from 'antd/es/table/interface';
import Tables from '@/components/tables/tables';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import { MetahumanResource, TabKeys } from '@/types/metahuman';
import { Button } from '@/components/eai-design';
import Modals from '@/components/modals/Modals';
import MetahumanModal from './metahuman-modal';
import metahumanService from '@/api/services/metahumanService';
import { useRequest } from 'ahooks';
import { SvgIcon } from '@/components/icon';

const { Text } = Typography;


interface AppTableProps {
  dataSource: MetahumanResource[];
  tabValue: TabKeys;
  loading?: boolean;
  refresh?: () => void;
}

const AppTable: React.FC<AppTableProps> = ({ dataSource, loading = false, tabValue, refresh }) => {
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [isLimitModalVisible, setIsLimitModalVisible] = useState(false);
  const [currentApp, setCurrentApp] = useState<MetahumanResource | null>(null);
  const [newLimit, setNewLimit] = useState<number>(0);

  const [connectionError, setConnectionError] = useState<string>('');
  const [maxConnectionLimit, setMaxConnectionLimit] = useState<number>(10);

  const [expandedRows, setExpandedRows] = useState<Record<string, boolean>>({});
  const contentRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const [overflowRowMap, setOverflowRowMap] = useState<Record<string, boolean>>({});
  const containerRef = useRef<HTMLDivElement>(null);
  const [containerSize, setContainerSize] = useState<{ width: number; height: number }>({ width: 0, height: 0 });
  
  // 检测内容是否超出2行
  useEffect(() => {
    const map: Record<string, boolean> = {};
    dataSource.forEach((item) => {
      const el = contentRefs.current[item.appId];
      if (el) {
        const style = window.getComputedStyle(el);
        const lineHeightPx = style.lineHeight;
        let lineHeight = 0;
        if (lineHeightPx.endsWith('px')) {
          lineHeight = parseFloat(lineHeightPx);
        } else {
          // 退化处理：无法解析时使用字体大小的 1.2 倍
          const fontSize = parseFloat(style.fontSize || '14');
          lineHeight = fontSize * 1.2;
        }
        const maxTwoLinesHeight = lineHeight * 2 + 1; // 误差补偿
        map[item.appId] = el.scrollHeight > maxTwoLinesHeight;
      }
    });
    setOverflowRowMap(map);
  }, [dataSource, containerSize.width]);
  
  // 监听容器尺寸变化
  useEffect(() => {
    if (!containerRef.current) return;
    
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width, height } = entry.contentRect;
        setContainerSize({ width, height });
      }
    });
    
    resizeObserver.observe(containerRef.current);
    
    return () => {
      resizeObserver.disconnect();
    };
  }, []);
  
  const toggleRowExpansion = (key: string) => {
    setExpandedRows((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  
  // 分页状态管理
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 分页处理函数
  const handlePaginationChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
    // 分页变化时清空选中状态，避免跨页选择问题
    setSelectedRowKeys([]);
  };

  // 计算分页后的数据（如果分页后无数据且当前页不为1，则自动跳转到上一页）
  const paginatedData = useMemo(() => {
    const startIdx = (currentPage - 1) * pageSize;
    const endIdx = currentPage * pageSize;
    const pageData = dataSource.slice(startIdx, endIdx);
    // 如果当前页无数据且不是第一页，自动跳转到上一页
    if (pageData.length === 0 && currentPage > 1) {
      setCurrentPage(currentPage - 1);
      return dataSource.slice((currentPage - 2) * pageSize, (currentPage - 1) * pageSize);
    }
    return pageData;
  }, [dataSource, currentPage, pageSize]);

  // 计算连接率
  const calculateConnectionRate = (active: number, max: number) => {
    if (max === 0) return 0;
    return Math.round((active / max) * 100);
  };

  // 获取连接率状态
  const getConnectionStatus = (rate: number) => {
    if (rate >= 80) return { color: 'var(--error-color)', icon: 'ai-metahuman-danger', status: 'high' };
    if (rate >= 60) return { color: 'var(--warning-color)', icon: 'ai-metahuman-warning', status: 'medium' };
    return { color: 'var(--success-color)', icon: 'ai-metahuman-success', status: 'low' };
  };

  // 处理行选择
  const handleRowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: Key[], selectedRows: MetahumanResource[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
    // 添加全选/取消全选功能
    onSelectAll: (selected: boolean, selectedRows: MetahumanResource[], changeRows: MetahumanResource[]) => {
      if (selected) {
        // 只选择当前页的数据
        const currentPageKeys = paginatedData.map(item => item.appId as Key);
        setSelectedRowKeys(currentPageKeys);
      } else {
        setSelectedRowKeys([]);
      }
    },
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    if (selectedRowKeys.length === paginatedData.length) {
      // 如果当前页全部选中，则取消全选
      setSelectedRowKeys([]);
    } else {
      // 否则全选当前页
      const currentPageKeys = paginatedData.map(item => item.appId as Key);
      setSelectedRowKeys(currentPageKeys);
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) return;
    
    try {
      // 显示确认弹窗
      const confirmed = await new Promise<boolean>((resolve) => {
        Modal.confirm({
          title: '确认删除',
          content: `确定要删除选中的 ${selectedRowKeys.length} 个应用吗？此操作不可恢复。`,
          okText: '确定',
          cancelText: '取消',
          okType: 'danger',
          onOk: () => resolve(true),
          onCancel: () => resolve(false),
        });
      });

      if (!confirmed) return;

      // 循环删除选中的应用
      await Promise.allSettled(
        selectedRowKeys.map(async (key) => {
          const appId = key.toString();
          return deletePermission(appId);
        })
      );
      // 清空选中状态
      setSelectedRowKeys([]);

      // 刷新数据
      refresh?.();
    } catch (error) {
      console.error('批量删除失败:', error);
      message.error({ content: '批量删除失败，请重试', key: 'batchDelete' });
    }
  };

  // 调整连接上限
  const handleAdjustLimit = (record: MetahumanResource) => {
    setCurrentApp(record);
    setNewLimit(record.maxConnections);
    setIsLimitModalVisible(true);
  };

  // 确认调整上限
  const handleConfirmLimit = async () => {
    if (!currentApp || newLimit <= 0) {
      message.error('请输入有效的连接上限');
      return;
    }

    if (!validateConnectionLimit(newLimit)) {
      return;
    }

    try {
      await updatePermission(currentApp.appId, newLimit);
      message.success('连接上限调整成功');
      setIsLimitModalVisible(false);
      setCurrentApp(null);
      setNewLimit(0);
      refresh?.();
    } catch (error) {
      message.error('连接上限调整失败');
    }
  };

  // 取消调整上限
  const handleCancelLimit = () => {
    setIsLimitModalVisible(false);
    setCurrentApp(null);
    setNewLimit(0);
  };

  // 删除应用，新增二次确认
  const handleDelete = async (record: MetahumanResource) => {
    Modal.confirm({
      title: '确认删除该应用？',
      content: '删除后该应用将无法使用数字人功能，是否继续？',
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deletePermission(record.appId);
          message.success('删除成功');
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  // 根据tab值动态生成列配置
  const getColumns = () => {
    if (tabValue === TabKeys.PERMISSION) {
      return [
        {
          title: '应用名称',
          dataIndex: 'appName',
          key: 'appName',
          width: 260,
          render: (text: string, record: MetahumanResource) => (
            <div className="flex items-center gap-3">
              <AvatarDisplay 
                src={record.appAvatar} 
                className="h-[32px] max-h-[32px] w-[32px] max-w-[32px]" 
                size={32} 
              />
              <span className="font-semibold text-text-5">{text}</span>
            </div>
          ),
        },
        // {
        //   title: '应用描述',
        //   dataIndex: 'appDescription',
        //   key: 'appDescription',
        //   width: 300,
        //   render: (text: string) => (
        //     <div className="max-w-[280px]">
        //       {text ? (
        //         <div 
        //           className="text-text-5"
        //         >
        //           {text}
        //         </div>
        //       ) : (
        //         <span className="text-gray-400">暂无描述</span>
        //       )}
        //     </div>
        //   ),
        // },
        {
          title: '应用描述',
          dataIndex: 'appDescription',
          key: 'appDescription',
          render: (text: string, record: MetahumanResource) => {
            const isExpanded = expandedRows[record.appId] || false;
    
            return (
              <>
                <div
                  className={`${
                    !isExpanded ? 'line-clamp-2' : ''
                  }   w-full overflow-hidden  text-ellipsis  `}
                >
                  <div
                    ref={(el) => {
                      contentRefs.current[record.appId] = el;
                    }}
                    className="text-sm text-text-5"
                  >
                    {record.appDescription}
                  </div>
                </div>
                {overflowRowMap[record.appId] && (
                  <div className="cursor-pointer">
                    {!isExpanded ? (
                      <div
                        className="flex items-center justify-start gap-1 text-sm text-text-3"
                        onClick={() => toggleRowExpansion(record.appId)}
                      >
                        <DownOutlined style={{ fontSize: '12px' }}/>
                        展开
                      </div>
                    ) : (
                      <div
                        className="flex items-center justify-start gap-1 text-sm text-text-3"
                        onClick={() => toggleRowExpansion(record.appId)}
                      >
                        <UpOutlined style={{ fontSize: '12px' }}/>
                        收起
                      </div>
                    )}
                  </div>
                )}
              </>
            );
          },
        },
        {
          title: '连接上限',
          dataIndex: 'maxConnections',
          key: 'maxConnections',
          width: 160,
          render: (text: number) => (
            <span className="text-text-5">{text}</span>
          ),
        },
        {
          title: '操作',
          key: 'action',
          width: 172,
          render: (_: any, record: MetahumanResource) => (
            <Space size="middle">
              <AntdButton
                type="text"
                icon={<EditOutlined />}
                onClick={() => handleAdjustLimit(record)}
                className="text-blue-600 hover:text-blue-800"
              >
                调整上限
              </AntdButton>
              <AntdButton
                type="text"
                icon={<DeleteOutlined />}
                onClick={() => handleDelete(record)}
                className="text-red-600 hover:text-red-800"
              >
                删除
              </AntdButton>
            </Space>
          ),
        },
      ];
    } else {
      // USAGE 模式
      return [
        {
          title: '应用名称',
          dataIndex: 'appName',
          key: 'appName',
          width: 260,
          render: (text: string, record: MetahumanResource) => (
            <div className="flex items-center gap-3">
              <AvatarDisplay 
                src={record.appAvatar} 
                className="h-[32px] max-h-[32px] w-[32px] max-w-[32px]" 
                size={32} 
              />
              <span className="font-semibold text-text-5">{text}</span>
            </div>
          ),
        },
        // {
        //   title: '应用描述',
        //   dataIndex: 'appDescription',
        //   key: 'appDescription',
        //   width: 300,
        //   render: (text: string) => (
        //     <div className="max-w-[280px]">
        //       {text ? (
        //         <div 
        //           className="text-text-5"
        //         >
        //           {text}
        //         </div>
        //       ) : (
        //         <span className="text-text-5">暂无描述</span>
        //       )}
        //     </div>
        //   ),
        // },
        {
          title: '应用描述',
          dataIndex: 'appDescription',
          key: 'appDescription',
          render: (text: string, record: MetahumanResource) => {
            const isExpanded = expandedRows[record.appId] || false;
    
            return (
              <>
                <div
                  className={`${
                    !isExpanded ? 'line-clamp-2' : ''
                  }   w-full overflow-hidden  text-ellipsis  `}
                >
                  <div
                    ref={(el) => {
                      contentRefs.current[record.appId] = el;
                    }}
                    className="text-sm text-text-5"
                  >
                    {record.appDescription}
                  </div>
                </div>
                {overflowRowMap[record.appId] && (
                  <div className="cursor-pointer">
                    {!isExpanded ? (
                      <div
                        className="flex items-center justify-start gap-1 text-sm text-text-3"
                        onClick={() => toggleRowExpansion(record.appId)}
                      >
                        <DownOutlined style={{ fontSize: '12px' }}/>
                        展开
                      </div>
                    ) : (
                      <div
                        className="flex items-center justify-start gap-1 text-sm text-text-3"
                        onClick={() => toggleRowExpansion(record.appId)}
                      >
                        <UpOutlined style={{ fontSize: '12px' }}/>
                        收起
                      </div>
                    )}
                  </div>
                )}
              </>
            );
          },
        },
        {
          title: '数字人连接率',
          key: 'connectionRate',
          width: 320,
          render: (_: any, record: MetahumanResource) => {
            const rate = calculateConnectionRate(record.activeConnections, record.maxConnections);
            const status = getConnectionStatus(rate);
            
            return (
              <div className="flex items-center gap-2">
                <SvgIcon
                  icon={status.icon}
                  size={16}
                />
                <Progress
                  percent={rate}
                  size="small"
                  strokeColor={status.color}
                  showInfo={false}
                  className="flex-1"
                />
                <span className="text-sm font-medium text-text-5" style={{ color: status.color }}>
                  {rate}%
                </span>
              </div>
            );
          },
        },
        {
          title: '连接人数',
          dataIndex: 'activeConnections',
          key: 'activeConnections',
          width: 160,
          render: (text: number) => (
            <span className="text-text-5">{text}</span>
          ),
        },
        {
          title: '连接上限',
          dataIndex: 'maxConnections',
          key: 'maxConnections',
          width: 160,
          render: (text: number) => (
            <span className="text-text-5">{text}</span>
          ),
        },
      ];
    }
  };

  // 创建数字人权限
  const { runAsync: createPermission, loading: createLoading } = useRequest(
    async (appIds: string[], maxConnections: number) => {
      const response = await metahumanService.createMetahumanPermission({
        appIds,
        maxConnections
      });
      return response;
    },
    {
      manual: true, // 手动触发，不自动执行
      onSuccess: () => {
        refresh?.();
      },
      onError: (error) => {
        console.error('创建数字人权限失败:', error);
      }
    }
  );

  // 更新数字人权限
  const { runAsync: updatePermission, loading: updateLoading } = useRequest(
    async (appId: string, maxConnections: number) => {
      const response = await metahumanService.updateMetahumanPermission({
        appId,
        maxConnections
      });
      return response;
    },
    {
      manual: true, // 手动触发，不自动执行
      onSuccess: () => {
        refresh?.();
      },
      onError: (error) => {
        console.error('更新数字人权限失败:', error);
      }
    }
  );

  // 删除数字人权限
  const { runAsync: deletePermission, loading: deleteLoading } = useRequest(
    async (appId: string) => {
      const response = await metahumanService.deleteMetahumanPermission({
        appId
      });
      return response;
    },
    {
      manual: true, // 手动触发，不自动执行
      onSuccess: () => {
        refresh?.();
      },
      onError: (error) => {
        console.error('删除数字人权限失败:', error);
      }
    }
  );

  const handleModalOk = async (selectedApps: MetahumanResource[], maxConnections: number) => {
    try {
      // 根据 dataSource 去重，避免重复添加
      const uniqueSelectedApps = selectedApps.filter(
        app => !dataSource.some(item => item.appId === app.appId)
      );
      const appIds = uniqueSelectedApps.map(app => app.appId);
      
      // 调用创建权限API
      await createPermission(appIds, maxConnections);
      setIsAddModalVisible(false);
    } catch (error) {
      console.error('添加应用失败:', error);
    }
  };

  // 获取最大连接数限制
  useEffect(() => {
    const fetchConnectionLimit = async () => {
      try {
        const response = await metahumanService.getMetahumanConnectionLimit();
        setMaxConnectionLimit(response.limit);
      } catch (error) {
        console.error('获取连接限制失败:', error);
        // 如果API调用失败，使用默认值
        setMaxConnectionLimit(10);
      }
    };

    if (isLimitModalVisible) {
      fetchConnectionLimit();
    } else {
      setMaxConnectionLimit(10);
      setConnectionError('');
    }
  }, [isLimitModalVisible]);

  const validateConnectionLimit = (value: number): boolean => {
    if (value <= 0) {
      setConnectionError('连接数必须大于0');
      return false;
    }
    if (value > maxConnectionLimit) {
      setConnectionError('人数超过最大上限');
      return false;
    }
    setConnectionError('');
    return true;
  };

  return (
    <div className={`w-full ${tabValue === TabKeys.USAGE ? 'h-[calc(100vh-185px)]' : 'h-[calc(100vh-280px)]'}`} ref={containerRef}>
      <div className="mb-4">
        <span className="font-normal text-[14px] text-[var(--text-primary)] flex items-center">
          {tabValue === TabKeys.USAGE ? (
            <>
              <p className="text-@brand-color font-semibold mr-1">{dataSource.length}</p>
              个应用正在使用数字人
            </>
          ) : null}
          {tabValue === TabKeys.PERMISSION && (
            <div className="flex items-center justify-between w-full">
              <div className="flex items-center">
                已授权 <p className="text-@brand-color font-semibold mx-1">{dataSource.length}</p>
                个应用可开启数字人
              </div>
              <div className="flex items-center gap-3">
                {selectedRowKeys.length > 0 ? (
                  <>
                    {/* <AntdButton
                      onClick={handleSelectAll}
                      className="flex items-center gap-1"
                    >
                      {selectedRowKeys.length === dataSource.length ? '取消全选' : '全选'}
                    </AntdButton>
                    <AntdButton
                      onClick={() => setSelectedRowKeys([])}
                      className="flex items-center gap-1"
                    >
                      清空选择
                    </AntdButton> */}
                    <AntdButton
                      danger
                      onClick={handleBatchDelete}
                      className="flex items-center gap-1"
                    >
                      批量删除 ({selectedRowKeys.length})
                    </AntdButton>
                  </>
                ) : (
                  <span className="text-gray-500 text-sm"></span>
                )}
                <Button icon={<PlusOutlined />} onClick={()=>{setIsAddModalVisible(true)}} className="!border !border-@brand-color !text-@brand-color">
                  添加应用
                </Button>
              </div>
            </div>
          )}
        </span>
      </div>
      <Tables
        columns={getColumns()}
        dataSource={paginatedData}
        loading={loading}
        rowKey="appId"
        rowSelection={tabValue === TabKeys.PERMISSION ? handleRowSelection : undefined}
        paginationProps={{
          total: dataSource.length,
          current: currentPage,
          pageSize: pageSize,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: handlePaginationChange,
        }}
      />
      <MetahumanModal
        open={isAddModalVisible}
        onOk={handleModalOk}
        onCancel={()=>{setIsAddModalVisible(false)}}
        existingApps={dataSource}
      />
      <Modals
        open={isLimitModalVisible}
        onOk={handleConfirmLimit}
        onCancel={handleCancelLimit}
        title="设置数字人连接数量"
        okText="确定"
        cancelText="取消"
        confirmLoading={updateLoading}
        destroyOnHidden={true}
      >
        <div className="space-y-2">
          <Text className="text-[14px] text-text-4">
            连接上限（人）
            <div className="text-text-3 text-[12px]">
              最大上限{maxConnectionLimit}
            </div>
          </Text>
          <InputNumber
            min={1}
            value={newLimit}
            onChange={(value) => {
              setNewLimit(value || 0);
              validateConnectionLimit(value || 0);
            }}
            placeholder="请输入连接上限"
            className={`!w-full ${connectionError ? 'border-red-600 border' : ''}`}
            status={newLimit > maxConnectionLimit ? 'error' : ''}
          />
          {connectionError && (
          <Text
            style={{ fontSize: '12px', color: '#ff4d4f', display: 'block' }}
          >
            {connectionError}
          </Text>
        )}
        </div>
      </Modals>
    </div>
  );
};

export default AppTable; 